package stack;

public class ArrayStackDemo {
    public static void main(String[] args) {
        //功能测试
        ArrayStack arrayStack = new ArrayStack(4);
        if(arrayStack.isEmpty()){
            System.out.println("栈空");
        }else {
            System.out.println("栈不空");
        }
        if(arrayStack.isFull()){
            System.out.println("栈满");
        }else {
            System.out.println("栈不满");
        }
        arrayStack.push(1);
        arrayStack.push(2);
        arrayStack.push(3);
        arrayStack.push(4);
        System.out.println(1111111);
        arrayStack.list();
        System.out.println(2222222);
        arrayStack.push(5);
        arrayStack.list();
        if(arrayStack.isEmpty()){
            System.out.println("栈空");
        }else {
            System.out.println("栈不空");
        }
        if(arrayStack.isFull()){
            System.out.println("栈满");
        }else {
            System.out.println("栈不满");
        }

        try {
            arrayStack.pop();
            arrayStack.list();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            arrayStack.pop();
            arrayStack.pop();
            arrayStack.pop();
            arrayStack.pop();
        } catch (Exception e) {
            e.printStackTrace();
        }

        arrayStack.list();
        if(arrayStack.isEmpty()){
            System.out.println("栈空");
        }else {
            System.out.println("栈不空");
        }
        if(arrayStack.isFull()){
            System.out.println("栈满");
        }else {
            System.out.println("栈不满");
        }
    }
}

// 栈的数组实现
class ArrayStack {
    private int maxsize;// 栈的大小
    private int[] stack;// 数组模拟栈
    private int top = -1;//初始化栈顶

    public ArrayStack(int maxsize){
        this.maxsize = maxsize;
        stack = new int[this.maxsize];
    }

    //判断栈满
    public boolean isFull(){
        return top == maxsize-1;
    }

    //判断栈空
    public boolean isEmpty(){
        return top == -1;
    }
    //入栈
    public void push(int value){
        if(isFull()){
            System.out.println("栈满");
            return;
        }
        top = top+1;
        stack[top] = value;
        System.out.println("入栈成功,入栈元素为"+value);
    }

    //出栈
    public int pop(){
        if(isEmpty()){
            throw new RuntimeException("栈空，不能再出栈啦~~");
        }
        int value = stack[top];
        top = top-1;
        return value;
    }
    
    //遍历栈
    public void list(){
        if(isEmpty()){
            System.out.println("栈空，没有数据~~");
            return;
        }
        for (int i = top; i >= 0 ; i--) {
            System.out.printf("stack[%d]=%d\n",i,stack[i]);
        }
    }
}
